package com.zn.handler;

import com.zn.common.exception.MyException;
import com.zn.common.resp.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * 验证参数 , 异常处理 , 返回json
 * 因为前后端不分离了, 暂时不使用 可自定义返回json  或者 跳转页面
 */
@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public Object allExceptionHandler(Exception e) {
        ApiResult<String> result = new ApiResult<>();
        ModelAndView model = new ModelAndView();
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            BindingResult bindingResult = ex.getBindingResult();
            StringBuilder errMsg = new StringBuilder(bindingResult.getFieldErrors().size() * 16);
            errMsg.append("Invalid request:");
            for (int i = 0; i < bindingResult.getFieldErrors().size(); i++) {
                if (i > 0) {
                    errMsg.append(",");
                }
                FieldError error = bindingResult.getFieldErrors().get(i);
                errMsg.append(error.getField() + ":" + error.getDefaultMessage());
            }
            result.setCode(500);
            result.setMessage(errMsg.toString());
            return result;
        }else if(e instanceof MyException){
            MyException ex = (MyException) e;
            e.printStackTrace();
            model.addObject("code", ex.getCode());
            model.addObject("message", ex.getMessage());
            if(ex.getCode() == 702){
                model.setViewName("login");
                return model;
            }else{
                result.setCode(ex.getCode());
                result.setMessage(ex.getMessage());
                return result;
            }
        }else{
            e.printStackTrace();
            result.setCode(500);
            result.setMessage(e.getCause().getMessage());
            return result;
        }
    }
}